# 启动服务的命令（需要在终端执行）
# uvicorn main:app --reload

import time
from fastapi import FastAPI, HTTPException, Body, Query, Request, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import OAuth2PasswordBearer
from jwt_utils import create_access_token, verify_token
from service import UserServiceImpl
from vo import UserInfo, UserRegisterAndLogin


base_content = '<p>I am testing data, I am testing data.</p><p><img src="https://example.com/image.png"></p>'
image_uri = 'https://example.com/image.png'

app = FastAPI()
# 添加 CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://127.0.0.1:9527"],  # 或 ["*"] 允许所有域名
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有方法（GET, POST, OPTIONS, 等）
    allow_headers=["*"],  # 允许所有请求头
)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

user_svc = UserServiceImpl()

@app.post("/user/register")
async def register(user: UserRegisterAndLogin):
    res = user_svc.user_register(user.user_name, user.user_password)
    if res is None:
        raise HTTPException(status_code=400, detail="用户已存在")
    else:
        return {
            "code": 200,
            "data": res
        }


@app.post("/user/login")
async def login(user: UserRegisterAndLogin):
    res = user_svc.user_login(user.user_name, user.user_password)
    if res is None:
        raise HTTPException(status_code=400, detail="用户不存在或密码错误")
    else:
        access_token = create_access_token(data={"sub": user.user_name, "time": time.time()})
        return {
            "code": 200,
            "data": {"access_token": access_token, "token_type": "bearer", "user_info": res}
        }


@app.get("/user/info")
async def get_user_info(user_id: str, token: str = Depends(oauth2_scheme)):
   res = user_svc.get_user_info(user_id)
   if res is None:
       raise HTTPException(status_code=400, detail="用户不存在")
   else:
       payload = verify_token(token)
       if not payload:
           raise HTTPException(
               status_code=401,
               detail="Invalid token",
               headers={"WWW-Authenticate": "Bearer"},
           )
       return {
            "code": 200,
            "data": res
        }